package com.examples.jmsexamples;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Description 点对点
 * @Author benjamin
 * @Date 2020/1/21 13:58
 * @Version
 */
public class QueueConsumer {


    public final static String USERNAME = ActiveMQConnection.DEFAULT_USER;

    public final static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    public final static String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    /**
     * 1、 创建连接工厂
     * 2、 创建连接
     * 3、 启动连接
     * 4、 创建会话
     * 5、创建队列，作为消费目的地
     * 6、创建消费者
     * 7、消费者实现监听接口消费消息
     * 8、关闭资源
     */
    public static void main(String[] args) {

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_URL);

        try {
            Connection connection = factory.createConnection();
            connection.start();
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("activemq-queue-test1");
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        String text = textMessage.getText();
                        System.out.println("msg: " + text);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                    try {
                        session.commit();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 故意不让线程退出
            Thread.sleep(100 * 1000L);

            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
